package translation

import sugarbind_input.*;
import parser.IupacParser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern

import org.apache.tools.ant.filters.FixCrLfFilter.RemoveEofFilter;
import org.eurocarbdb.application.glycanbuilder.BuilderWorkspace;
import org.eurocarbdb.application.glycanbuilder.Glycan;
import org.eurocarbdb.application.glycanbuilder.GlycanRenderer;
import org.eurocarbdb.application.glycanbuilder.GlycanRendererAWT;
import org.eurocarbdb.application.glycanbuilder.GlycoCTCondensedParser;
import org.eurocarbdb.application.glycanbuilder.MassOptions;
import org.eurocarbdb.application.glycanbuilder.SVGUtils;




class TranslationService {
	

	Map ligandTypes = new HashMap<String, Ligand_Type>()
	
	def setLigandTypes(){
		
//		String sial = "dgro-dgal-NON"
//		String fuco = "lgal-HEX-1:5|6:d"
		
		ligandTypes.put("dgro-dgal-NON", Ligand_Type.findByLigand_Type_Name("Sialylated") )
		ligandTypes.put("sulfate", Ligand_Type.findByLigand_Type_Name("Sulfated") )
		
		//ligandTypes.put("lgal-HEX-1:5|6:d", Ligand_Type.findByLigand_Type_Name("Fucosylated") )
		ligandTypes.put("lgal-HEX-1:5-6:d", Ligand_Type.findByLigand_Type_Name("Fucosylated") )
		ligandTypes.put("fluoro", Ligand_Type.findByLigand_Type_Name("Fluorinated") )
		ligandTypes.put("phosphate", Ligand_Type.findByLigand_Type_Name("Phosphorylated") )		
//		println("ligandTypes : $ligandTypes")
	}
	
	def glycoCT(String iupac) {
		
//		iupac = removeCer(iupac)
		IupacParser p= new IupacParser(iupac.trim());

		try
		{
			p.getCtTree(p.parse());
			System.out.println("");
			System.out.println("IUPAC sequence : ");
			System.out.println(p.getIupacSequence());
			System.out.println("");
			System.out.println("CT sequence : ");
			System.out.println(p.getCtSequence());
		}
		catch(Exception ex)
		{
			System.err.println("Problem parsing the sequence");
			ex.printStackTrace();
		}
		return p.getCtSequence()
	}
	
//	def removeCer(String iupac)
//	{
//		def cer = "Cer"
//		if(iupac.contains(cer))
//		{
//			iupac = iupac.substring(0,iupac.indexOf(cer))
//		}
//		return iupac
//	}
	
	def cartoon(Structure structure, String cartoonFormat, String picFormat ) {
		
		String filename = null
		try{
			//The workspace will initialise dictionaries and placement libraries for us
			BuilderWorkspace workspace=new BuilderWorkspace(new GlycanRendererAWT());
			workspace.setNotation(cartoonFormat)//cfg | cfgbw | uoxf | uoxfcol | text
			
			//Get a reference to the renderer
			GlycanRenderer renderer=workspace.getGlycanRenderer();
			
			//Get an instance of the GlycoCT Parser
			GlycoCTCondensedParser parser=new GlycoCTCondensedParser(false);
			MassOptions options=MassOptions.empty();
			
			//Parse in a GlycoCT condensed string from text and pass in empty MassOptions
			Glycan glycan=parser.fromGlycoCTCondensed(structure.glycoct, options);
			
			//Generate a list of glycans to render
			List<Glycan> glycanList=new ArrayList<>();
			glycanList.add(glycan);
			
			//Render glycans as a PNG (last parameter)
			filename = "cartoons/"+structure.id+"_"+cartoonFormat + "." + picFormat
			SVGUtils.export((GlycanRendererAWT) renderer, filename , glycanList, false, true, picFormat);
		}
		catch(Exception ex)
		{
			System.err.println("Translation service error for " + Structure.toString());
		}
		return filename
	}
	
	def ligand_type(Ligand ligand)
	{
		setLigandTypes()
		
		
		println("ligand : $ligand ${ligand.ligand_Types}")
		
		String glycoct = ligand.structure.glycoct
		glycoct = glycoct.replace('\n', '')
		glycoct = glycoct.replace('|', '-')
		
//		println("glycoct : $glycoct")
		
		for ( String key : ligandTypes.keySet() ) {
			
			ligand.ligand_Types.remove(ligandTypes.get(key))
			String regex = ".*${key}.*"
//			println("key : $key / regex : $regex")
					
			if(glycoct.matches(regex))
			{
//				println("Key OK!")
				ligand.ligand_Types.add(ligandTypes.get(key))
			}			
		}
		
		println("ligand : $ligand ${ligand.ligand_Types}")
		ligand.validate()
		ligand.save(flush:true)
		
		return ligand
	}
}
